package com.lagou.zk;
import cn.hutool.json.JSONUtil;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ZkJdbc {
    private static JDBCParam jdbcParam = new JDBCParam("jdbc:mysql://centos7-3:3306/test?characterEncoding=utf-8&useSSL=false","root","12345678");
    private static Connection con =null;

    public static void main(String[] args) throws InterruptedException {
        ZkClient zkClient = new ZkClient("centos7-1:2181");
        System.out.println("zkclient is ready");
        zkClient.setZkSerializer(new ZkStrSerializer());
        getNewConnection();
        boolean exists = zkClient.exists("/jdbc");
        if(!exists){
            zkClient.createPersistent("/jdbc",JSONUtil.toJsonStr(jdbcParam));
        }

        zkClient.subscribeDataChanges("/jdbc", new IZkDataListener() {
            public void handleDataChange(String path, Object o) throws Exception {
                System.out.println(path+"data is changed"+o.toString());
                String s = o.toString();
                JDBCParam newJdbc = JSONUtil.toBean(s, JDBCParam.class);
                jdbcParam.setPassword(newJdbc.getPassword());
                jdbcParam.setName(newJdbc.getName());
                jdbcParam.setUrl(newJdbc.getUrl());
                getNewConnection();
            }

            //数据节点删除
            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path+"data is delete");
            }

        });
        Thread.sleep(Integer.MAX_VALUE);
    }


    public static void getNewConnection(){
        try {
            if(con!=null){
                con.close();
            }
            con = DriverManager.getConnection(jdbcParam.getUrl() , jdbcParam.getName() , jdbcParam.getPassword());
            System.out.println(String.format("连接成功：host：%s name:%s password:%s",jdbcParam.getUrl() , jdbcParam.getName() , jdbcParam.getPassword()));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
